<template>
  <div>
    <div class="userHeader">
      <el-button type="primary" @click="handleAdd()">新增</el-button>
      <div class="userRight">
        <el-input
          v-model="input"
          style="width: 240px"
          placeholder="请输入用户名"
          clearable
        />
        <el-button type="primary" @click="searchEven()">搜索</el-button>
      </div>
    </div>
    <div class="userWrap">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="name" label="姓名" width="180" />
        <el-table-column prop="age" label="年龄" width="180" />
        <el-table-column prop="sexLabel" label="性别" />
        <el-table-column prop="birth" label="出生日期" />
        <el-table-column prop="addr" label="地址" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editOper(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" size="small" @click="deletOper(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="userFooter">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="config.total"
          @current-change="changePage"
        />
      </div>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="action === 'add' ? '新增用户' : '编辑用户'"
      width="35%"
      :before-close="handleClose"
    >
      <!-- 需要注意的是设置了：inline="true"
    会对el-select的样式造成影响，我们通过设置一个class=select-clearn
    在css进行处理 -->
      <el-form :inline="true" :model="formUser" :rules="rules" ref="userForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="formUser.name"
                placeholder="请输入姓名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input
                v-model="formUser.age"
                placeholder="请输入年龄"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="select-clearn" label="性别" prop="sex">
              <el-select v-model="formUser.sex" placeholder="请选择性别">
                <el-option label="男" value="1"></el-option>
                <el-option label="女" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birth">
              <el-date-picker
                v-model="formUser.birth"
                type="date"
                placeholder="请选择出生日期"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="地址" prop="addr">
            <el-input
              v-model="formUser.addr"
              placeholder="请输入地址"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row style="justify-content: flex-end">
          <el-form-item>
            <el-button type="primary" @click="handleClose">取消</el-button>
            <el-button type="primary" @click="onSubmit">确定</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted, reactive,nextTick  } from "vue";
const { proxy } = getCurrentInstance();

const input = ref("");
const tableData = ref([]);
const config = reactive({
  name: "",
  total: 0,
});
const formUser = reactive({
  id: "",
  name: "",
  age: "",
  sex: "1",
  birth: "",
  addr: "",
});
const action = ref("add");
const dialogVisible = ref(false);

const getUserList = async () => {
  const res = await proxy.$api.getUserData(config);
  config.total = res.total;
  //   console.log(res);

  tableData.value = res.list.map((item) => ({
    ...item,
    sexLabel: item.sex === 1 ? "男" : "女",
  }));
};
const rules = reactive({
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  age: [
    { required: true, message: "请输入年龄", trigger: "blur" },
    // { min: 1, max: 100, message: "年龄在 1 到 100 岁", trigger: "blur" },
  ],
  sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
  birth: [{ required: true, message: "请选择出生日期", trigger: "blur" }],
  addr: [{ required: true, message: "请输入地址", trigger: "blur" }],
});

const handleClose = () => {
  // 获取表单重置
  proxy.$refs.userForm.resetFields();
  dialogVisible.value = false;
};
const timeFormat = (date) => {
  var time = new Date(date);
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  function add(m) {
    return m < 10 ? "0" + m : m;
  }
  // var h = time.getHours();
  // var mm = time.getMinutes();
  // var s = time.getSeconds();
  return y + "-" + add(m) + "-" + add(d);
};
const onSubmit = () => {
  // 表单验证
  proxy.$refs.userForm.validate(async (valid) => {
    if (valid) {
      let res = null;
      // 生日的正则验证
      formUser.birth = /^\d{4}-\d{2}-\d{2}$/.test(formUser.birth)
        ? formUser.birth
        : timeFormat(formUser.birth);
      if (action.value === "edit") {
        res = await proxy.$api.updateUser(formUser);
      } else {
        res = await proxy.$api.addUser(formUser);
      }
      // console.log(res);
      if (res) {
        dialogVisible.value = false;
        proxy.$refs.userForm.resetFields();
        getuserDate();
        ElMessage({
          type: "success",
          message: "提交成功",
          showClose: true,
        });
      } else {
        ElMessage({
          type: "error",
          message: "提交失败,请输入正确的内容",
          showClose: true,
        });
      }
      // await proxy.$api.addUser(formUser).then(() => {
      //   ElMessage({
      //   type: "success",
      //   message: "提交成功",
      //   showClose: true,
      // });
      // dialogVisible.value = false;
      // getuserDate();
      // })
    }
  });
};
const editOper = (value) => {
    dialogVisible.value = true;
  action.value = "edit";
  
  // Object.assign(formUser, { ...value, sex: "" + value.sexLabel });
  // for (let key in formUser) {
  //   formUser[key] = value[key];
  //   formUser['sex'] = value['sexLabel']
  //   console.log(formUser);
  // }
  nextTick(() => {
    Object.assign(formUser, { ...value, sex: "" + value.sexLabel });
  });
};
const deletOper = (value) => {
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await proxy.$api.deleteUser({ id: value.id });
    ElMessage({
      type: "success",
      message: "删除成功",
      showClose: true,
    });
    getuserDate();
  });
};

const handleAdd = () => {
  dialogVisible.value = true;
  action.value = "add";
};
const searchEven = () => {
  config.name = input.value;
  getUserList();
};
const changePage = (val) => {
  config.page = val;
  getUserList();
};
onMounted(() => {
  getUserList();
});
</script>

<style scoped lang="less">
.userHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-right: 30px;
  .el-input {
    margin-right: 20px;
  }
}
.userWrap {
  padding-bottom: 60px;
  position: relative;
  .userFooter {
    position: absolute;
    bottom: 0px;
    right: 50px;
  }
}
</style>
